<template>
  <div class="merchant-layout">
    <!-- 左侧菜单 -->
    <div class="sidebar" :class="{ 'sidebar-collapsed': isCollapsed }">
      <div class="logo">
        <h2 v-if="!isCollapsed">万代校园商户</h2>
        <h2 v-else>商户</h2>
      </div>

      <el-menu
        :default-active="$route.path"
        class="sidebar-menu"
        :collapse="isCollapsed"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        router
      >
        <el-menu-item index="/merchant/labor-publish">
          <i class="el-icon-edit-outline"></i>
          <span slot="title">劳务发布</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content" :class="{ expanded: isCollapsed }">
      <!-- 顶部导航栏 -->
      <div class="header">
        <div class="header-left">
          <el-button
            type="text"
            @click="toggleSidebar"
            class="sidebar-toggle"
            title="切换菜单"
          >
            <i class="el-icon-s-fold" v-if="!isCollapsed"></i>
            <i class="el-icon-s-unfold" v-else></i>
          </el-button>
          <span class="page-title">{{ currentPageTitle }}</span>
        </div>

        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="merchant-info">
              <i class="el-icon-user-solid"></i>
              {{ merchantInfo.name || merchantInfo.username || '商户' }}
              <i class="el-icon-arrow-down"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-area">
        <router-view />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "MerchantLayout",
  data() {
    return {
      isCollapsed: false,
      merchantInfo: {}
    }
  },
  mounted() {
    // 从localStorage恢复菜单折叠状态
    const savedCollapsed = localStorage.getItem('merchantSidebarCollapsed')
    if (savedCollapsed !== null) {
      this.isCollapsed = JSON.parse(savedCollapsed)
    } else {
      this.isCollapsed = false
    }
  },
  computed: {
    currentPageTitle() {
      const titleMap = {
        "/merchant/labor-publish": "劳务发布"
      }
      return titleMap[this.$route.path] || "劳务发布"
    }
  },
  async created() {
    // 先尝试从localStorage获取商户信息
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      try {
        this.merchantInfo = JSON.parse(userInfo)
        this.$store.dispatch("login", this.merchantInfo)
      } catch (error) {
        console.error("解析商户信息失败:", error)
      }
    }

    // 然后尝试从API获取最新信息
    await this.loadMerchantInfo()
  },
  methods: {
    toggleSidebar() {
      this.isCollapsed = !this.isCollapsed
      // 保存菜单折叠状态到localStorage
      localStorage.setItem('merchantSidebarCollapsed', JSON.stringify(this.isCollapsed))
    },

    handleCommand(command) {
      switch (command) {
        case "profile":
          this.$message.info("个人信息功能开发中")
          break
        case "changePassword":
          this.$message.info("修改密码功能开发中")
          break
        case "logout":
          this.logout()
          break
      }
    },

    async loadMerchantInfo() {
      try {
        const response = await this.$http.get("/merchant/info")
        if (response.data.code === 200) {
          this.merchantInfo = response.data.data
          this.$store.dispatch("login", this.merchantInfo)
          // 更新localStorage
          localStorage.setItem('userInfo', JSON.stringify(this.merchantInfo))
        }
      } catch (error) {
        console.error("获取商户信息失败:", error)
        // 如果API调用失败，使用localStorage中的数据
        if (!this.merchantInfo.username) {
          const userInfo = localStorage.getItem('userInfo')
          if (userInfo) {
            try {
              this.merchantInfo = JSON.parse(userInfo)
            } catch (e) {
              console.error("解析localStorage中的商户信息失败:", e)
            }
          }
        }
      }
    },

    async logout() {
      try {
        await this.$http.post("/merchant/logout")
      } catch (error) {
        console.error("退出登录API调用失败:", error)
      } finally {
        localStorage.removeItem("token")
        localStorage.removeItem("userInfo")
        localStorage.removeItem("userType")
        this.$store.dispatch("logout")
        this.$message.success("退出登录成功")
        this.$router.push("/login")
      }
    }
  }
}
</script>

<style scoped>
.merchant-layout {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 左侧菜单 */
.sidebar {
  width: 180px !important;
  min-width: 180px;
  max-width: 180px;
  background-color: #304156;
  overflow: hidden;
  flex-shrink: 0;
}

.sidebar.sidebar-collapsed {
  width: 50px !important;
  min-width: 50px;
  max-width: 50px;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2b3a4b;
  color: white;
  margin-bottom: 0;
}

.logo h2 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.sidebar-menu {
  border: none;
  height: calc(100vh - 60px);
  overflow-y: auto;
  width: 100% !important;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 100% !important;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.main-content.expanded {
  margin-left: 0;
}

/* 顶部导航栏 */
.header {
  height: 60px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.sidebar-toggle {
  margin-right: 10px;
  font-size: 18px;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.header-right {
  display: flex;
  align-items: center;
}

.merchant-info {
  cursor: pointer;
  color: #666;
  display: flex;
  align-items: center;
  gap: 8px;
}

.merchant-info:hover {
  color: #409EFF;
}

/* 内容区域 */
.content-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 确保菜单宽度固定 */
.sidebar * {
  box-sizing: border-box;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    left: -250px;
    top: 0;
    height: 100vh;
    z-index: 1000;
    width: 250px !important;
  }

  .sidebar.sidebar-collapsed {
    left: 0;
    width: 64px !important;
  }

  .main-content {
    margin-left: 0;
  }
}
</style>